<template>
  <!-- 编辑储售企业 表单 -->
  <a-modal
    v-model:open="visible"
    title="编辑储售企业"
    @ok="handleOk"
    class="addStation"
    destroyOnClose
    :width="520"
    @cancel="cancel"
    centered
  >
    <a-form
      :model="form"
      :rules="rules"
      layout="inline"
      :labelCol="labelCol"
      ref="formRef"
    >
      <a-form-item label="电站名称" name="stationId">
        <a-select
          ref="select"
          v-model:value="form.stationId"
          class="formInput"
          placeholder="请选择"
          show-search
          optionFilterProp="label"
          disabled
          @change="changeStation"
        >
          <a-select-option
            v-for="item in stationList"
            :key="item.stationId"
            :value="item.stationId"
            :label="item.stationName"
            :title="item.stationName"
          >
            {{ item.stationName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="充电取数时段" name="chargingTime">
        <TimeRangeSelector
          v-model="form.chargingTime"
          @change="() => formRef.validateFields(['chargingTime'])"
        />
      </a-form-item>
      <a-form-item label="放电取数时段" name="dischargingTime">
        <TimeRangeSelector
          v-model="form.dischargingTime"
          @change="() => formRef.validateFields(['dischargingTime'])"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancel">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确认</a-button
        >
      </div>
    </template>
  </a-modal>
</template>
<script setup>

import TimeRangeSelector from "@/views/conpoments/TimeRangeSelector.vue"
import { isArray, isObject } from "lodash-es";
const $api = inject("$api");
const props = defineProps({
  editCompanyVisible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
  },
});
const loading = ref(false);
const visible = ref(props.editCompanyVisible);
const emits = defineEmits(["update:editCompanyVisible", "getConfigList"]);
watch(
  () => props.editCompanyVisible,
  (val) => {
    visible.value = val;
    if (val) {
      initForm();
      getStationList();
    }
  }
);
const labelCol = { style: { width: "120px" } };
const formRef = ref(null);
const form = ref({
  stationId: undefined,
  chargingTime: [],
  dischargingTime: [],
});
const rules = ref({
  stationId: [
    {
      required: true,
      message: "请选择电站",
      trigger: "change",
    },
  ],
  chargingTime: [
    {
      required: true,
      trigger: "blur",
      validator: (rule, value) => {
        if (form.value.chargingTime?.length === 0) {
          return Promise.reject("请选择时段");
        } else {
          return Promise.resolve();
        }
      },
    },
  ],
  dischargingTime: [
    {
      required: true,
      trigger: "blur",
      validator: (rule, value) => {
        if (form.value.dischargingTime?.length === 0) {
          return Promise.reject("请选择时段");
        } else {
          return Promise.resolve();
        }
      },
    },
  ],
});
const initForm = () => {
  if (props.rowData) {
    form.value = {
      stationId: props.rowData.stationId,
      chargingTime: props.rowData.chargingTime,
      dischargingTime: props.rowData.dischargingTime,
    };
    console.log("[ form.value ]-140", form.value);
  }
};
const cancel = () => {
  emits("update:editCompanyVisible", false);
  form.value = {
    stationId: undefined,
    chargingTime: [],
    dischargingTime: [],
  };
  formRef.value.clearValidate();
};
const handleSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      const chargingTime = form.value.chargingTime.map((item) => {
        if (isArray(item)) {
          return {
            startTime: item[0],
            endTime: item[1],
          };
        } else {
          return item;
        }
      });
      const dischargingTime = form.value.dischargingTime.map((item) => {
        if (isArray(item)) {
          return {
            startTime: item[0],
            endTime: item[1],
          };
        } else {
          return item;
        }
      });
      const params = {
        ...form.value,
        chargingTime,
        dischargingTime,
      };
      loading.value = true;
      const res = await $api.sellStorageSetTime(params);
      loading.value = false;
      if (res.code === 0) {
        message.success("编辑成功");
        cancel();
        emits("getConfigList");
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
};
const stationList = ref([]);
const getStationList = async () => {
  const res = await $api.companyStationtList();
  if (res && res.code === 0) {
    // 储能(energy_storage)：0-非储能企业；1-待建设；2-建设中；3-运行中；4-停运")，只渲染3和4的
    stationList.value = res.data?.filter(
      (item) => item.es === 3 || item.es === 4
    );
  }
};
</script>

<style lang="less" scoped>
.form {
  padding: 0 40px;
  margin-top: 30px;
}
.formInput,
.formSelect {
  width: 240px;
}
.ant-form-item {
  margin-top: 20px;
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
.addDate {
  margin-top: 10px;
}
.handleSaveDate {
  margin-left: 10px;
  font-size: 16px;
}
.tagConent {
  width: 390px;
}
.ant-tag {
  margin-top: 10px;
  display: inline-block;
}
</style>